package com.learn.service.webservice;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.jws.WebParam;

import com.learn.util.StringUtil;
import org.springframework.beans.BeanUtils;

import com.learn.service.dao.IBaseDao;
import com.learn.service.dm.UserInfoDM;
import com.learn.service.tb.user.User;

public class UserServiceImpl implements IUserService {

    @Resource(name = "baseDao")
    private IBaseDao<User> tUserDao;

    // 查询所有用户信息
    public List<UserInfoDM> getUserList(@WebParam(name = "userInfoDM") UserInfoDM userInfoDM) {
        if(null != userInfoDM.getUserName() && !StringUtil.isBlank(userInfoDM.getUserName())){
            String param = "%"+userInfoDM.getUserName()+"%";
            // 使用别名传参
            String hql = "from User u where u.userName like :username ";
            Map<String, Object> params = new HashMap<>();
            params.put("username",param);
            List<User> tbList = tUserDao.find(hql, params);
            List<UserInfoDM> listDm = getUserInfoListDM(tbList);
            return listDm;
        }else{
            String hql = "from User ";
            List<User> tbList = tUserDao.find(hql);
            List<UserInfoDM> listDm = getUserInfoListDM(tbList);
            return listDm;
            }
    }

    //根据用户ID查询用户信息
    public UserInfoDM getUserById(@WebParam(name = "userId") Integer userId) {
        // 使用?传参
        String hql = "from User where userId = ?0 ";
        User user = tUserDao.only(hql, userId);
        UserInfoDM userDM = new UserInfoDM();
        if (null != user) {
            BeanUtils.copyProperties(user, userDM);
            return userDM;
        }
        return null;
    }

    // 根据用户ID删除用户
    public int delUserById(@WebParam(name = "userId") Integer userId) {
        User userInfo = new User();
        userInfo.setUserId(userId);
        tUserDao.delete(userInfo);
        return 1;
    }

    // 新增用户
    public int addUser(@WebParam(name = "userInfoDM") UserInfoDM userInfoDM) {
        User userInfo = new User();
        if (null != userInfoDM) {
            BeanUtils.copyProperties(userInfoDM, userInfo);
        }
        tUserDao.save(userInfo);
        return 1;
    }

    //数据转换
    private List<UserInfoDM> getUserInfoListDM(List<User> listUsers){
        List<UserInfoDM> listDm = new ArrayList<UserInfoDM>();
        if (null != listUsers) {
            for (User tb : listUsers) {
                UserInfoDM tDm = new UserInfoDM();
                BeanUtils.copyProperties(tb, tDm);
                listDm.add(tDm);
            }
        }
        return listDm;
    }
}